using System;
using System.IO;
using System.Threading.Tasks;
using NewApp.Backend.Api.Entity;
using NewApp.Backend.Api.Repository;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using NewApp.Backend.Api.Params;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace NewApp.Backend.Api.Controllers
{

    [ApiController]
    [Route("[Controller]")]
    public class PictureController : ControllerBase
    {

        private IHostEnvironment _hostingEnvironment;
        private IRepository<PictureInfo> _pictureInfoIRepository;


        private dynamic PicturePath;
        public PictureController(
            IHostEnvironment hostingEnvironment,
            IRepository<PictureInfo> pictureInfoIRepository
            )
        {
            _hostingEnvironment = hostingEnvironment;
            _pictureInfoIRepository = pictureInfoIRepository;
        }

        public ActionResult Index()
        {
            //获取或设置包含应用程序内容文件的目录的绝对路径。
            var filesPath = _hostingEnvironment.ContentRootPath;

            //将获取的路径的反斜杠转成斜杠
            PicturePath = filesPath.Replace('\\', '/');

            Console.WriteLine(PicturePath);

            return null;
        }

        [HttpGet]
        public dynamic Getfiles([FromQuery] Pager pager)
        {

            // get请求默认从url中获取参数，如果需要使用实体接收参数，需要FromQuery特性
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;
            var users = _pictureInfoIRepository.Table;

            var u = users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();


            return new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                Msg = "获取图片路径成功^_^"
            };
        }

        [HttpGet, Route("get")]
        public dynamic Get()
        {
            var users = _pictureInfoIRepository.Table;

            return new
            {
                Code = 1000,
                Data = users,
                Msg = "获取图片路径成功^_^"
            };
        }



        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var picture = _pictureInfoIRepository.GetById(id);
            return new
            {
                Code = 1000,
                Data = picture,
                Msg = "获取指定图片^_^"
            };
        }


        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {

            _pictureInfoIRepository.Delete(id);
            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除用户成功^_^"
            };
        }

        [HttpPut("{id}")]
        public dynamic Put(int id, CreatePicture updateUser)
        {


            var user = _pictureInfoIRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "要更新的用户不存在，请确认后重试=_="
                };
            }


            user.status = updateUser.status;


            _pictureInfoIRepository.Update(user);

            return new
            {
                Code = 1000,
                Data = user,
                Msg = "更新成功"
            };
        }





        [HttpPost, Route("files")]
        public async Task<IActionResult> UploadFiles()
        {
            Index();
            string filesPath = "";

            //Microsoft.AspNetCore.Http.FormFileCollection
            var files = Request.Form.Files;


            //将今天的日期作为相对路径创建一个子文件夹 比如 20210728
            string tempPath = DateTime.Now.ToString("yyyyMMdd");//相对路径

            string physicPath = PicturePath + "/wwwroot/";//物理路径

            //确定给定路径是否引用磁盘上的现有目录。
            if (!Directory.Exists(physicPath))
            {
                //在指定路径中创建所有目录和子目录,除非它们已经存在。 参数:要创建的目录
                Directory.CreateDirectory(physicPath);
            }

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    //新文件名字
                    string filesName = DateTime.Now.ToFileTime() + Path.GetExtension(formFile.FileName);

                    //Combine 拼接路径
                    string FullPath = Path.Combine(physicPath, filesName);

                    //将拼接完的路径中的反斜杠去掉
                    string fileFullPath = FullPath.Replace('\\', '/');

                    using (var stream = new FileStream(fileFullPath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);//保存文件
                    }

                    filesPath += filesName;

                    var picturesql = new PictureInfo
                    {
                        PictureName = formFile.FileName,
                        PicturePath = filesPath,
                        status = "不展示"
                    };
                    await _pictureInfoIRepository.InsertAsync(picturesql);
                }
            }

            return Ok(new { filesPath });


        }


        [HttpPost, Route("article")]
        public async Task<IActionResult> ArticleUploadFiles()
        {

            Index();
            string filesPath = "";

            // var article = _articlesIRepository.GetById(id);

            //Microsoft.AspNetCore.Http.FormFileCollection
            var files = Request.Form.Files;


            //将今天的日期作为相对路径创建一个子文件夹 比如 20210728
            string tempPath = DateTime.Now.ToString("yyyyMMdd");//相对路径

            string physicPath = PicturePath + "/wwwroot/";//物理路径

            //确定给定路径是否引用磁盘上的现有目录。
            if (!Directory.Exists(physicPath))
            {
                //在指定路径中创建所有目录和子目录,除非它们已经存在。 参数:要创建的目录
                Directory.CreateDirectory(physicPath);
            }

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    //新文件名字
                    string filesName = DateTime.Now.ToFileTime() + Path.GetExtension(formFile.FileName);

                    //Combine 拼接路径
                    string FullPath = Path.Combine(physicPath, filesName);

                    //将拼接完的路径中的反斜杠去掉
                    string fileFullPath = FullPath.Replace('\\', '/');

                    using (var stream = new FileStream(fileFullPath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);//保存文件
                    }

                    filesPath += filesName;



                }
            }

            return Ok(new { filesPath });


        }
        // 富文本图片上传
        [HttpPost, Route("uploadWangEditor")]
        public dynamic uploadWangEditor()
        {


            Index();
            var url = "";

            // var article = _articlesIRepository.GetById(id);

            //Microsoft.AspNetCore.Http.FormFileCollection
            var files = Request.Form.Files;


            //将今天的日期作为相对路径创建一个子文件夹 比如 20210728
            string tempPath = DateTime.Now.ToString("yyyyMMdd");//相对路径

            string physicPath = PicturePath + "/wwwroot/";//物理路径

            //确定给定路径是否引用磁盘上的现有目录。
            if (!Directory.Exists(physicPath))
            {
                //在指定路径中创建所有目录和子目录,除非它们已经存在。 参数:要创建的目录
                Directory.CreateDirectory(physicPath);
            }

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    //新文件名字
                    string filesName = DateTime.Now.ToFileTime() + Path.GetExtension(formFile.FileName);

                    //Combine 拼接路径
                    string FullPath = Path.Combine(physicPath, filesName);

                    //将拼接完的路径中的反斜杠去掉
                    string fileFullPath = FullPath.Replace('\\', '/');

                    using (var stream = new FileStream(fileFullPath, FileMode.Create))
                    {
                        formFile.CopyTo(stream);//保存文件
                    }

                    url += filesName;


                }
            }

            List<PictureArticle> PictureArticle = new List<PictureArticle>();

            PictureArticle.Add(new PictureArticle
            { 
                Url = "http://localhost:5000/" + url,
                Alt = "上传成功",
                Href = "http://localhost:5000/" + url
            });


            var res = new
            {
                // errno 即错误代码，0 表示没有错误。
                //如果有错误，errno != 0，可通过下文中的监听函数 fail 拿到该错误码进行自定义处理
                errno = 0,

                //data 是一个数组，返回图片Object，Object中包含需要包含url、alt和href三个属性,它们分别代表图片地址、图片文字说明和跳转链接,alt和href属性是可选的，可以不设置或设置为空字符串,需要注意的是url是一定要填的。
                data = PictureArticle,

            };

            return res;

        }






    }
}